# coding=utf-8
from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session

from info import constants, db
from info.models import User, News, Category
from info.utils.commom import user_login_data
from info.utils.image_storage import image_storage
from info.utils.response_code import RET
from . import admin_blue

import time
from datetime import datetime,timedelta

# ending

# 新闻分类添加/修改
# 请求路径: /admin/add_category
# 请求方式: POST
# 请求参数: id,name
# 返回值:errno,errmsg
@admin_blue.route('/add_category', methods=['POST'])
def add_category():
    #1, 获取参数
    category_id = request.json.get("id")
    category_name = request.json.get("name")

    #2, 校验参数
    if not category_name:
        return jsonify(errno=RET.PARAMERR,errmsg="分类名称不能为空")

    #3, 数据入库
    if category_id: #修改(编辑)

        #3,1 获取分类对象,判断
        try:
            category = Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="获取分类失败")

        if not category:
            return jsonify(errno=RET.NODATA,errmsg="分类不存在")

        #3,2 修改分类名字
        category.name = category_name

    else: #增加
        category = Category()
        category.name = category_name

        try:
            db.session.add(category)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="添加分类失败")

    #4, 返回响应
    return jsonify(errno=RET.OK,errmsg="success")

# 新闻分类管理
# 请求路径: /admin/news_category
# 请求方式: GET
# 请求参数: GET,无
# 返回值:GET,渲染news_type.html页面, data数据
@admin_blue.route('/news_category')
def news_category():

    #1,查询分类
    try:
        categories =  Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取失败")

    category_list = []
    for category in categories:
        category_list.append(category.to_dict())

    #2,携带分类数据,渲染页面
    return render_template('admin/news_type.html',categories=category_list)

# 获取/设置新闻版式编辑详情
# 请求路径: /admin/news_edit_detail
# 请求方式: GET, POST
# 请求参数: GET, news_id, POST(news_id,title,digest,content,index_image,category_id)
# 返回值:GET,渲染news_edit_detail.html页面,data字典数据, POST(errno,errmsg)
@admin_blue.route('/news_edit_detail', methods=['GET', 'POST'])
def news_edit_detail():
    #1,判断请求方式,如果是GET,携带新闻数据渲染页面
    if request.method == "GET":

        #1.1获取新闻编号
        news_id = request.args.get("news_id")

        #1.2查询新闻对象,判断
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html',data={"errmsg":"新闻查询失败"})

        if not news:
            return render_template('admin/news_edit_detail.html', data={"errmsg": "新闻不存在"})

        #1.3查询分类数据
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html', data={"errmsg": "分类获取失败"})
        category_list = []
        for category in categories:
            category_list.append(category.to_dict())

        #1.4携带新闻数据,渲染页面
        return render_template('admin/news_edit_detail.html',data={"news_info":news.to_dict(),"categories":category_list})
    # 2,如果是POST请求
    # 2.1 获取参数
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    news_id = request.form.get("news_id")

    # 2.2 校验参数
    # 为空校验
    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 上传图片,并判断
    try:
        image_name = image_storage(index_image.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="七牛云异常")

    if not image_name:
        return jsonify(errno=RET.NODATA, errmsg="上传失败")

    # 判断新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/news_edit_detail.html', data={"errmsg": "新闻查询失败"})

    if not news:
        return render_template('admin/news_edit_detail.html', data={"errmsg": "新闻不存在"})

    # 2.3 数据入库(改变新闻内容)
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.content = content

    # 2.4 返回响
    pass
    return jsonify(errno=RET.OK, errmsg="success")

# 请求路径: /admin/news_review_detail
# 请求方式: GET,POST
# 请求参数: GET, news_id, POST,news_id, action
# 返回值:GET,渲染news_review_detail.html页面,data字典数据
@admin_blue.route('/news_review_detail', methods=['GET', 'POST'])
def news_review_detail():
    #1,判断请求方式,如果是GET,携带新闻数据渲染页面
    if request.method == "GET":

        #1.1获取新闻编号
        news_id = request.args.get("news_id")

        #1.2查询新闻对象,判断
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_review_detail.html',data={"errmsg":"新闻查询失败"})

        if not news:
            return render_template('admin/news_review_detail.html', data={"errmsg": "新闻不存在"})

        #1.3携带新闻数据,渲染页面
        return render_template('admin/news_review_detail.html',data={"news_info":news.to_dict()})
    #2,如果是POST请求
    #2.1 获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    #2.2 校验参数
    #为空校验
    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    #操作类型校验
    if not action in ["accept","reject"]:
        return jsonify(errno=RET.DATAERR, errmsg="操作有误")

    #查询新闻,判断是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询失败")

    if not news:
        return jsonify(errno=RET.NODATA,errmsg="新闻不存在")

    #2.3 数据入库(改变新闻status)
    if action == "accept":
        news.status = 0
    else:
        news.status = -1
        news.reason = request.json.get("reason","")

    #2.4 返回响应
    return jsonify(errno=RET.OK,errmsg="success")

# 新闻版式编辑列表
# 请求路径: /admin/news_edit
# 请求方式: GET
# 请求参数: GET, page, keywords
# 返回值:GET,渲染news_edit.html页面,data字典数据
@admin_blue.route('/news_edit')
def news_edit():
    #1, 获取参数page
    page=  request.args.get("page","1")
    keyword=  request.args.get("keyword")

    #2, 参数转换
    try:
        page = int(page)
    except Exception as e:
        page = 1

    #3, 获取新闻
    try:

        #判断是否有查询的关键字
        condition = []

        if keyword:
            condition.append(News.title.contains(keyword))

        paginate = News.query.filter(*condition).order_by(News.create_time.desc()).paginate(page,10,False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取用户失败")

    #4,数据拼接
    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    news_list = []
    for news in items:
        news_list.append(news.to_review_dict())

    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_list":news_list
    }

    #5, 返回响应
    return render_template('admin/news_edit.html',data=data)

# 获取新闻审核列表
# 请求路径: /admin/news_review
# 请求方式: GET
# 请求参数: GET, page,keyword
# 返回值:渲染user_list.html页面,data字典数据
@admin_blue.route('/news_review')
def news_review():
    #1, 获取参数page
    page=  request.args.get("page","1")
    keyword=  request.args.get("keyword")

    #2, 参数转换
    try:
        page = int(page)
    except Exception as e:
        page = 1

    #3, 获取用户
    try:
        paginate = News.query.filter(News.status !=0 ).order_by(News.create_time.desc()).paginate(page,2,False)

        #判断是否有查询的关键字
        condition = [News.status !=0]

        if keyword:
            condition.append(News.title.contains(keyword))

        paginate = News.query.filter(*condition).order_by(News.create_time.desc()).paginate(page,2, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取用户失败")

    #4,数据拼接
    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    news_list = []
    for news in items:
        news_list.append(news.to_review_dict())

    data = {
        "total_page":total_page,
        "current_page":current_page,
        "news_list":news_list
    }

    #5, 返回响应
    return render_template('admin/news_review.html',data=data)

# 用户列表
# 请求路径: /admin/user_list
# 请求方式: GET
# 请求参数: p
# 返回值:渲染user_list.html页面,data字典数据
@admin_blue.route('/user_list')
@user_login_data
def user_list():
    #1, 获取参数page
    page = request.args.get("page","1")

    #2, 参数转换
    try:
        page = int(page)
    except Exception as e:
        page = 1

    #3, 获取用户
    try:
        paginate = User.query.filter(User.is_admin==False).order_by(User.create_time.desc()).paginate(page,10,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取用户失败")

    #4,数据拼接
    total_page = paginate.pages
    current_page = paginate.page
    items = paginate.items

    user_list = []
    for user in items:
        user_list.append(user.to_admin_dict())

    data = {
        "total_page":total_page,
        "current_page":current_page,
        "user_list":user_list
    }

    #5, 返回响应
    return render_template('admin/user_list.html',data=data)

# 用户统计
# 请求路径: /admin/user_count
# 请求方式: GET
# 请求参数: 无
# 返回值:渲染页面user_count.html,字典数据
@admin_blue.route('/user_count')
def user_count():
    #1,查询总人数
    try:
        total_count = User.query.filter(User.is_admin==False).count()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/user_count.html', data={"errmsg":"查询总人数失败"})

    #2,查询月活人数
    time_local = time.localtime()
    mon_date_str = "%d-%d-1" % (time_local.tm_year, time_local.tm_mon)  # 2019-5-1
    mon_date_time = datetime.strptime(mon_date_str, "%Y-%m-%d")  # 2019-05-01 00:00:00
    try:
        mon_count = User.query.filter(User.last_login >= mon_date_time,User.is_admin==False).count()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/user_count.html', data={"errmsg":"查询月活失败"})

    #3,查询日活人数
    day_date_str = "%d-%d-%d" % (time_local.tm_year, time_local.tm_mon, time_local.tm_mday)  # 2019-5-1
    day_date_time = datetime.strptime(day_date_str, "%Y-%m-%d")  # 2019-05-01 00:00:00
    try:
        day_count = User.query.filter(User.last_login >= day_date_time).count()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/user_count.html', data={"errmsg":"查询日活失败"})

    #4,记录活跃时间段内的人数
    active_date = [] #记录活跃日期
    active_count = [] #记录活跃人数
    for i in range(0,7):
        #当天开始时间A
        begin_date = day_date_time - timedelta(days=i)

        #当天开始时间, 的后⼀一天B 
        end_date = day_date_time - timedelta(days=i-1)

        #添加当天开始时间字符串串到, 活跃⽇日期中
        active_date.append(begin_date.strftime("%Y-%m-%d"))

        #查询时间A到B这⼀一天的注册⼈人数 
        everyday_active_count = User.query.filter(User.is_admin==False,User.last_login>=begin_date,User.last_login<=end_date).count()

        #添加当天注册⼈人数到,获取数量量中
        active_count.append(everyday_active_count)

    #为了显示图标方便,反转容器
    active_date.reverse()
    active_count.reverse()

    #携带数据,渲染页面
    data = {
        "total_count":total_count,
        "mon_count":mon_count,
        "day_count":day_count,
        "active_date":active_date,
        "active_count":active_count
    }

    return render_template('admin/user_count.html', data=data)

# 后台主页内容
# 请求路径: /admin/index
# 请求方式: GET
# 请求参数: 无
# 返回值:渲染页面index.html,user字典数据
@admin_blue.route('/index')
@user_login_data
def admin_index():

    #判断用户是否是管理员
    # if not session.get("is_admin"):
    #     return redirect('/')
    return render_template('admin/index.html',user=g.user.to_dict())

# 获取/登陆,管理员登陆
# 请求路径: /admin/login
# 请求方式: GET,POST
# 请求参数:GET,无, POST,username,password
# 返回值: GET渲染login.html页面, POST,login.html页面,errmsg
@admin_blue.route('/login',methods=["GET","POST"])
def admin_login():
    #1, 判断请求方式,如果是GET请求直接返回页面
    if request.method == "GET":
        #判断用户是否有登陆过
        if session.get("is_admin"):
            return redirect('/admin/index')

        return render_template("admin/login.html")

    #2,如果post
    #2.1 获取参数
    username = request.form.get("username")
    password = request.form.get("password")

    #2.2 校验参数
    #为空校验
    if not all([username,password]):
        return render_template("admin/login.html",errmsg="参数不全")

    #密码校验
    try:
        admin = User.query.filter(User.nick_name == username,User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="该用户失败")

    if not admin:
        return render_template("admin/login.html", errmsg="该用户不存在")

    if not admin.check_passowrd(password):
        return render_template("admin/login.html", errmsg="密码出错了")

    # 2.3 状态保持
    session["user_id"] = admin.id
    session["nick_name"] = username
    session["is_admin"] = True

    # 2.4 返回响应
    # return redirect("http://www.taobao.com")
    return redirect("/admin/index")